import tkinter as tk
from tkinter import scrolledtext
from tkinter.messagebox import *
import requests
import logging
from tkinter import ttk
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import time
from tkinter import messagebox

# 查询相关的URL和代理配置
find_todo_box_url = "http://136.64.71.234:30121/aiops/api/v1/flow/tj/constructionWorkTable/getGzConstructionInfo"
find_formIdAndPid_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFlowForm"
find_broadband_info_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFormData"
proxies = {
    "http": "http://136.64.71.234:30121",
    "https": "http://136.64.71.234:30121"
}

def step_one_get_base_data(access_code, headers):
    payload = {
        "accessNo": access_code,
        "type": "A",
        "page": 0,
        "pageSize": 12
    }
    try:
        response = requests.post(find_todo_box_url, headers=headers, json=payload, proxies=proxies, timeout=(5, 30))
        if response.status_code == 200:
            re = response.json()
            if re and "content" in re:
                for key in re.get("content", []):
                    result_param = {
                        "flow_id": key.get("flow_id"),
                        "access_no": key.get("access_no"),
                        "address": key.get("address"),
                        "url": key.get("url")
                    }
                    return result_param
        else:
            logging.error(f"获取 接入号: {access_code} 的基础数据失败, 状态码: {response.status_code}, 响应内容: {response.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None

def getFormIdAndPid(result_param, headers):
    params = {'flowId': result_param.get("flow_id")}
    try:
        step_two_result = requests.get(find_formIdAndPid_url, headers=headers, params=params, proxies=proxies, timeout=(5, 30))
        if step_two_result.status_code == 200:
            step_two_result = step_two_result.json()
            if step_two_result:
                table_root = step_two_result["table"]
                for table in table_root:
                    for t_tmp in table.get("field", {}):
                        if t_tmp.get("fieldName") == "REQUEST_ID":
                            result_param["pId"] = t_tmp.get("value")
                        if t_tmp.get("fieldName") == "product_list_tab":
                            a = t_tmp.get("value")
                            result_param["formId"] = a.get("formId")
            return result_param
        else:
            logging.error(f"获取 接入号: {result_param.get('access_no')} 的 Form-Pid 数据失败, 状态码: {step_two_result.status_code}, 响应内容: {step_two_result.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None

def getBroadbandData(step_two_result, headers):
    params = {'formId': step_two_result.get("formId"), "pId": step_two_result.get("pId"), "pageNum": 0, "pageSize": 5}
    try:
        step_three_result = requests.get(find_broadband_info_url, headers=headers, params=params, proxies=proxies, timeout=(5, 30))
        if step_three_result.status_code == 200:
            step_three_result = step_three_result.json()
            if len(step_three_result) > 0:
                access_number = []
                only_broadband_account = []
                data = step_three_result['data']
                for result_temp in data:
                    access_number.append(result_temp["accessNo"])
                    if result_temp["productTypeId"] == "9":
                        only_broadband_account.append(result_temp["accessNo"])
                access_number_unique = list(set(access_number))
                step_two_result["accounts"] = access_number_unique
                only_broadband_account_unique = list(set(only_broadband_account))
                if only_broadband_account_unique:
                    step_two_result["broadband_account"] = only_broadband_account_unique
                else:
                    step_two_result["broadband_account"] = step_two_result["access_no"]
                return step_two_result
        else:
            logging.error(f"获取 接入号: {step_two_result.get('access_no')} 的宽带详情数据失败")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None
def process_data():
    # 处理宽带账号列表中的数据
    lines = broad_result_text.get("1.0", tk.END).strip().split('\n')

    # 初始化变量以检查是否存在多元素行
    multiple_elements_found = False

    # 处理每一行，提取出每一个项
    processed_lines = []
    for line in lines:
        # 去掉序号（通过找到第一个点来分割）
        content = line.split('. ', 1)[-1]
        # 去掉大括号和引号，并拆分成单个项目
        items = content.replace("[", "").replace("]", "").replace("'", "") # .split(", ")

        # 检查是否存在多元素行
        if ',' in content:
            multiple_elements_found = True

        # 将每个项目添加到结果列表中
        processed_lines.extend(items)
    # 如果存在多元素行，弹出提示框
    if multiple_elements_found:
        messagebox.showinfo("提示", "检测到某些行包含多个账号, 请自行甄别")

    # 将处理后的内容重新写回 broad_result_text，每个项目一行
    broad_result_text.delete("1.0", tk.END)  # 清空现有内容
    broad_result_text.insert("1.0", "\n".join(processed_lines))

def submit():
    access_codes = access_number_text.get("1.0", tk.END).strip().split('\n')
    cookie = cookie_text.get("1.0", tk.END).strip()
    headers = {"Content-Type": "application/json;charset=UTF-8", "Cookie": cookie}

    log_text.config(state="normal")
    log_text.delete("1.0", tk.END)  # 清空日志区域
    result_text.delete("1.0", tk.END)  # 清空结果区域
    log_text.config(state="disabled")

    total_codes = len(access_codes)
    for idx, access_code in enumerate(access_codes, start=1):
        result_param_1 = step_one_get_base_data(access_code.strip(), headers)
        if result_param_1:
            step_two_result = getFormIdAndPid(result_param_1, headers)
            if step_two_result:
                finalResult = getBroadbandData(step_two_result, headers)
                if finalResult:
                    log_text.config(state="normal")
                    log_output1 = f"{idx}. 查询接入号: {access_code} 成功\n"
                    log_text.insert(tk.END, log_output1)
                    log_text.config(state="disabled")

                    result_output = f"{idx}. 地址: {finalResult.get('address', '无')} --- 账号列表: {finalResult.get('accounts', '无')} \n"
                    result_text.insert(tk.END, result_output)

                    # 新增一列数据列
                    broad_result_text_output = f"{idx}. {finalResult.get('broadband_account', '无')} \n"
                    broad_result_text.insert(tk.END, broad_result_text_output)
                else:
                    log_text.config(state="normal")
                    output1 = f"{idx}. 查询接入号: {access_code} 失败: 3\n"
                    log_text.insert(tk.END, output1)
                    log_text.config(state="disabled")
                    result_text.insert(tk.END, output1)
                    broad_result_text.insert(tk.END, output1)
            else:
                log_text.config(state="normal")
                output1 = f"{idx}. 查询接入号: {access_code} 失败: 2\n"
                log_text.insert(tk.END, output1)
                log_text.config(state="disabled")
                result_text.insert(tk.END, output1)
                broad_result_text.insert(tk.END, output1)
        else:
            log_text.config(state="normal")
            output1 = f"{idx}. 查询接入号: {access_code} 失败: 1\n"
            log_text.insert(tk.END, output1)
            log_text.config(state="disabled")
            result_text.insert(tk.END, output1)
            broad_result_text.insert(tk.END, output1)

        # 更新进度条
        progress_label.config(text=f"进度: {idx}/{total_codes}")
        result_text.update()
        log_text.update()

def copy_to_clipboard():
    # 获取文本框中的内容
    text = broad_result_text.get("1.0", tk.END).strip()
    # 将内容复制到剪贴板
    root.clipboard_clear()  # 清空剪贴板
    root.clipboard_append(text)  # 将文本添加到剪贴板
    messagebox.showinfo("提示", "内容已复制到剪贴板。")

def getCookie():
    try:
        # 设置 Chrome 驱动路径
        chrome_driver_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"  # 替换为你的 ChromeDriver 路径
        options = Options()
        options.add_argument("--start-maximized")  # 启动时最大化窗口
        options.add_argument("--disable-extensions")
        options.add_argument("--headless")
        options.add_argument("--disable-popup-blocking")


        # 创建 WebDriver 实例
        service = Service(chrome_driver_path)
        driver = webdriver.Chrome(service=service, options=options)

        print("打开浏览器成功")
        # 打开登录页面
        login_url = "http://136.64.71.234:30121/aiops/loginm/sign"  # 替换为实际的登录 URL
        driver.get(login_url)
        print("条i转")

        print("请手动登录，然后按 Enter 继续...")
        input("按 Enter 键继续...")

        # 获取 Cookie
        cookies = driver.get_cookies()
        cookie_str = "; ".join([f"{cookie['name']}={cookie['value']}" for cookie in cookies])

        # 打印并插入 Cookie
        print("Cookie:", cookie_str)
        cookie_text.delete("1.0", tk.END)  # 清空之前的 Cookie
        cookie_text.insert(tk.END, cookie_str)  # 插入新的 Cookie

        # 关闭浏览器
        driver.quit()
    except requests.RequestException as e:
        logging.error(f"获取 Cookie 失败: {e}")
        showerror(title="获取Cookie", message="获取失败,请手动到浏览器复制Cookie")


# GUI部分
root = tk.Tk()
root.title("旭旭小仙女的工具箱")
root.geometry("1200x600")

# 接入号标签和文本域
access_number_label = tk.Label(root, text="接入号(用换行分隔):")
access_number_label.place(x=10, y=10)

access_number_text = tk.Text(root, height=5, width=50)
access_number_text.place(x=150, y=10, width=600, height=100)

# Cookie标签和文本域
cookie_label = tk.Label(root, text="Cookie:")
cookie_label.place(x=10, y=120)

cookie_text = tk.Text(root, height=5, width=50)
cookie_text.place(x=150, y=120, width=600, height=100)

# 获取Cookie按钮
getCookie_button = tk.Button(root, text="获取Cookie", command=getCookie, state="disabled")
getCookie_button.place(x=150, y=230, width=300, height=30)

# 提交按钮
submit_button = tk.Button(root, text="提交", command=submit)
submit_button.place(x=460, y=230, width=290, height=30)

# 单独宽带账号显示区域
broad_result_label = tk.Label(root, text="宽带账号:")
broad_result_label.place(x=770, y=10)

broad_result_text = scrolledtext.ScrolledText(root, height=20, wrap=tk.NONE)
broad_result_text.place(x=845, y=10, width=275, height=250)

# 处理文本按钮
process_data_button = tk.Button(root, text="处理数据", command=process_data)
process_data_button.place(x=770, y=70, width=60, height=30)

# 一键复制按钮
copy_button = tk.Button(root, text="复制结果", command=copy_to_clipboard)
copy_button.place(x=770, y=120, width=60, height=30)

# 日志显示区域
log_label = tk.Label(root, text="日志:")
log_label.place(x=10, y=270)
log_text = scrolledtext.ScrolledText(root, height=20, state="disabled", bg="lightgray", width=30)
log_text.place(x=10, y=300, width=350, height=250)

# 结果显示区域
result_label = tk.Label(root, text="结果:")
result_label.place(x=370, y=270)
result_text = scrolledtext.ScrolledText(root, height=20, wrap=tk.NONE)
result_text.place(x=370, y=300, width=750, height=250)

# 水平滚动条的配置
h_scroll = ttk.Scrollbar(root, orient=tk.HORIZONTAL, command=result_text.xview, style="TScrollbar")
result_text.configure(xscrollcommand=h_scroll.set)
h_scroll.place(x=370, y=550, width=750)

# 进度条
progress_label = tk.Label(root, text="进度: 0/0")
progress_label.place(x=10, y=560)

# 启动主循环
root.mainloop()
